package Controllers

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"gPublic/Common"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type reInfo struct {
	Name            string   `json:"user_name"`
	Phone           string   `json:"weChat"`
	Mobile          string   `json:"mobile"`
	Email           string   `json:"email"`
	Age             int64    `json:"birth"`     // 时间戳
	WorkDate        int64    `json:"work_date"` // 参加工作时间 时间戳
	WorkSt          int      `json:"work_st"`   // 求职状态 1
	Gender          string   `json:"sex"`       // 字符串
	Salary          []string `json:"salary" `
	ExpectJob       string   `json:"expect_job"`
	ExpectJlocation string   `json:"expect_jlocation"`
}

// type SalaryArr struct {
// 	SalaryOne float64 `json:"salary2" `
// 	SalaryTwo float64 `json:"salary1" `
// }

func ResumeAnalysis(c *gin.Context) {

	url := "http://resumesdk.market.alicloudapi.com/ResumeParser"
	appcode := "f2b0df68b8774e2db5bea4b4ed500175"
	checkCode := c.PostForm("check_code")

	cr := Common.Md5(checkCode)

	if checkCode == "" || cr != "ef2afe0ea76c76b6b4b1ee92864c4d5c" {
		Common.ErrorResponse(c, Common.ERROR, "无权使用该功能！")
		return
	}

	file, err := c.FormFile("file")
	if err != nil {
		Common.ErrorResponse(c, Common.ERROR, "Failed to read file！")
		return
	}

	src, err := file.Open()
	if err != nil {
		Common.ErrorResponse(c, Common.ERROR, "Failed to read file！")
		return
	}

	defer src.Close()

	fileData, err := ioutil.ReadAll(src)
	if err != nil {
		Common.ErrorResponse(c, Common.ERROR, "Failed to read file content！")
		return
	}

	baseCont := base64.StdEncoding.EncodeToString(fileData)

	data := map[string]interface{}{
		"file_cont":   baseCont,
		"file_name":   file.Filename,
		"need_avatar": 0,
		"ocr_type":    1,
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		Common.ErrorResponse(c, Common.ERROR, err)
		return
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		Common.ErrorResponse(c, Common.ERROR, err)
		return
	}

	req.Header.Set("Authorization", "APPCODE "+appcode)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		Common.ErrorResponse(c, Common.ERROR, err)
		return
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		Common.ErrorResponse(c, Common.ERROR, err)
		return
	}

	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		Common.ErrorResponse(c, Common.ERROR, err)
		return
	}
	// fmt.Printf("%#v", result)

	var s []string
	if evalData, ok := result["eval"].(map[string]interface{}); ok {
		salaryFloat := evalData["salary"].(float64)                  // 将工资数据转换为 float64 类型
		s = append(s, strconv.FormatFloat(salaryFloat, 'f', -1, 64)) // 转换为字符串并添加到切片

		// 对工资数据加上 2000，并转换为字符串，再添加到切片中
		newSalary := salaryFloat + 2000
		s = append(s, strconv.FormatFloat(newSalary, 'f', -1, 64))
	}

	var b int64
	if birthdayValue, ok := result["result"].(map[string]interface{})["birthday"].(string); ok {
		// 拆分生日字符串为年份和月份
		birthdayParts := strings.Split(birthdayValue, ".")
		year, _ := strconv.Atoi(birthdayParts[0])
		month, _ := strconv.Atoi(birthdayParts[1])

		// 构建出生日期时间
		birthDate := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)

		// 计算出生日期时间戳（以每年10月1日作为出生日期）
		b = birthDate.Unix()
	} else {
		if ageValue, ok := result["result"].(map[string]interface{})["age"].(string); ok {
			currentYear := time.Now().Year() // 获取当前年份
			tmp, err := strconv.Atoi(ageValue)
			if err != nil {
				b = 946656000 // 2000年
			} else {
				targetYear := currentYear - tmp

				// 构建目标时间
				targetTime := time.Date(targetYear, 1, 1, 0, 0, 0, 0, time.UTC)

				// 计算目标时间的时间戳
				b = targetTime.Unix()
				// 转换为时间戳
				// b = fmt.Sprint(minusAge.Unix())
			}
		} else if ageInfoValue, ok := result["result"].(map[string]interface{})["age_inf"].(string); ok {
			currentYear := time.Now().Year() // 获取当前年份
			tmp, err := strconv.Atoi(ageInfoValue)
			if err != nil {
				b = 946656000
			} else {
				targetYear := currentYear - tmp
				targetTime := time.Date(targetYear, 1, 1, 0, 0, 0, 0, time.UTC)
				b = targetTime.Unix()
			}
		} else {
			b = 0
		}
	}

	var sex string = "2"
	if genderValue, ok := result["result"].(map[string]interface{})["gender"].(string); ok {
		if genderValue == "男" {
			sex = "1"
		}
	} else if genderInfoValue, ok := result["result"].(map[string]interface{})["gender_inf"].(string); ok {
		if genderInfoValue == "男" {
			sex = "1"
		}
	}

	var WorkDate int64
	if WorkDateValue, ok := result["result"].(map[string]interface{})["grad_time"].(string); ok {
		layout := "2006.01"
		t, _ := time.Parse(layout, WorkDateValue)
		WorkDate = t.Unix()
	}

	var na string
	if nameValue, ok := result["result"].(map[string]interface{})["name"].(string); ok {
		na = nameValue
	}

	var em string
	if emailValue, ok := result["result"].(map[string]interface{})["email"].(string); ok {
		em = emailValue
	}

	var pe string
	if phoneValue, ok := result["result"].(map[string]interface{})["phone"].(string); ok {
		pe = phoneValue
	}
	// Common.SuccessResponse(c, Common.SUCCESS, result)
	r := reInfo{
		Name:     na,
		Phone:    pe,
		Email:    em,
		Mobile:   pe,
		Age:      b,
		Gender:   sex,
		WorkSt:   1,
		WorkDate: WorkDate,
		Salary:   s,
	}
	Common.SuccessResponse(c, Common.SUCCESS, r)
}
